<?php

namespace ulue\ext\db;
use ulue\web\Model;

class RelateModelOperate extends Model
{
    public $queryColumns    = array();
    public $relateTables    = array();
    public $joinOn          = array(
        'join'          => array(),
        'on'            => array(),
        );
    public $condition       = 1;
    public $config          = array(
            'alias'     => 'T',
        );

    public function select($queryColumns=array(),$relateTables=array(),$join_on=array(),$condition)
    {

    }
    /**
     * 多表链接删除,主表请放在第一位
     * @param  [array] $queryColumn    [要查询的字段]
     * @param  [string|array] $tables    [多张表]
     * @param  array  $join_on    [join on 条件]
     * @param  [type] $condition [删除条件，多是主表的记录条件]
     * @param  [array] $config [方法的其他配置 ] array('alias'=>'T',)
     * @return [bool]            [description]
     */
    /* 使用：
        @example 1: 传入具体的需要关联的表名 和 join on 关联条件
    $queryColumn = array( 'id', 'title as b_title,userId', '*', 'id as gid', '*')
    $tables = 'Subject,SubjectBlock,SubjectBlockData,SubjectBlockGoods,SubjectBlockSubclass'
    $join_on = array(
        'join'  =>array('left','left','left','left'),
        'on'    =>array('id,subjectId' , 'id,blockId' , 'blockId,blockId' , 'blockId,blockId')
    )
    $condition = "id = '3'";
    $config  = array('alias'=>'T',)

    SubjectPubFunction::relateDelete($tables ,$join_on ,$condition);
        @example 2:  传入特殊的主表表名，会自动加上与之相关的附表 (Subject|SubjectBlock|SubjectBlockSubclass)
    SubjectPubFunction::relateDelete('Subject','',"id='3'");
    =====================生成的 SQL 语句=======================
    DELETE T1,T2,T3,T4,T5 FROM [[Subject]] T1
    LEFT JOIN [[SubjectBlock]] T2 ON T1.id = T2.subjectId
    LEFT JOIN [[SubjectBlockData]] T3 ON T2.id = T3.blockId
    LEFT JOIN [[SubjectBlockGoods]] T4 ON T3.blockId = T4.blockId
    LEFT JOIN [[SubjectBlockSubclass]] T5 ON T4.blockId = T5.blockId
    WHERE T1.id='3'
     */
    public function delete($relateTables=array(),$join_on=array(),$condition,$config=array())
    {
        $condition      = trim($condition);
        #不允许没有where条件 或 where 条件为 1
        if (empty($condition) || $condition==1) {return false;}
        #处理传入的表 和 join on 条件
        if ( !($arr_result = self::handleParams($tables,$join_on)) ) {
            return false;
        }

        $arr_table      = $arr_result['table'];
        $join_on        = $arr_result['join_on'];

        $str_del_table  = 'T1,';
        $str_join       = '';
        # 取出主表
        $main_table     = array_shift($arr_table);
        $table_num      = count($arr_table);

        # 循环,构建其它表的 JOIN 语句
        for ($i=0; $i < $table_num ; $i++) {
            $str_del_table  .= 'T'.($i+2) . ',';
            $str_on          = 'T'.($i+1).'.'. str_replace(',', ' = T'.($i+2).'.', $join_on[$i] );
            $str_join       .= ' LEFT JOIN '.$arr_table[$i].' T'.($i+2).' ON '.$str_on;
        }
        $str_del_table  = trim($str_del_table,',');
        $str_sql        = "DELETE {$str_del_table} FROM {$main_table} T1 {$str_join} WHERE T1.{$condition}";
        // md($arr_table,$str_sql,4);
        unset($arr_table,$join_on,$str_on,$str_del_table,$main_table,$str_join);
        #执行删除
        $result         = $this->query();
        return $result ? true : false;
    }

    // 处理传入参数，得到 需要删除记录的所有表 array 以及 join on 条件
    public function handleParams($queryColumns=array(),$tables,$join_on,$condition)
    {

        #传入了所有关系表 array
        if (is_string($tables) && strpos($tables, ',')!==false ) {
            $arr_result['table']    = explode(',', $tables);
            $arr_result['join_on']  = (array)$join_on;
        } else if (is_array($tables)) {
            $arr_result['table']    = $tables;
            $arr_result['join_on']  = (array)$join_on;
        } else {
                return false;

        }
        foreach ($arr_result['table'] as $key => $value) {
            $arr_result['table'][$key] = '[['.$value.']]';
        }
        return $arr_result;
    }

    public function buildRelateSql($option='select')
    {
        $option         = strtoupper(trim($option));
        $queryColumn    = $this->queryColumn;
        $arr_table      = $this->relateTables;
        $join_on        = $this->joinOn;
        $condition      = $this->condition;
        $config         = $this->config;


		$char			= $config['alias'];

        $str_del_table  = 'T1,';
        $str_join       = '';
        # 取出主表
        $main_table     = array_shift($arr_table);
        $table_num      = count($arr_table);

        # 循环,构建其它表的 JOIN 语句
        for ($i=0; $i < $table_num ; $i++) {
            $str_del_table  .= 'T'.($i+2) . ',';
            $str_on          = 'T'.($i+1).'.'. str_replace(',', ' = T'.($i+2).'.', $join_on[$i] );
            $str_join       .= ' LEFT JOIN '.$arr_table[$i].' T'.($i+2).' ON '.$str_on;
        }
        $str_del_table      = trim($str_del_table,',');
        $this->gdb->querySqlStr    = "{$option} {$str_del_table} FROM {$main_table} T1 {$str_join} WHERE T1.{$condition}";
        // md($arr_table,$str_sql,4);
        unset($arr_table,$join_on,$str_on,$str_del_table,$main_table,$str_join);
    }
}
